package com.example.readroomforpaging3.adapter

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.navigation.Navigation
import androidx.navigation.fragment.FragmentNavigator
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.readroomforpaging3.R
import com.example.readroomforpaging3.databinding.ArticleItemBinding
import com.example.readroomforpaging3.databinding.FragmentHomeBinding
import com.example.readroomforpaging3.model.Article
import com.google.android.material.transition.MaterialElevationScale

class ArticleAdapter :
    PagingDataAdapter<Article, ArticleAdapter.ViewHolder>(ArticleDiffCallback()) {

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
        val itemView = holder.item
        itemView.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt("position", position)
            val itemTransitionName = "item"
            val extras = FragmentNavigatorExtras(itemView to itemTransitionName)
            Navigation.findNavController(itemView)
                .navigate(R.id.action_homeFragment_to_detailFragment, bundle, null, extras)

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ArticleItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    class ViewHolder(binding: ArticleItemBinding) : RecyclerView.ViewHolder(binding.root) {
        private val tvName = binding.text
        val item = binding.item
        fun bind(article: Article?) {
            tvName.text = article?.title
            item.transitionName = "item_${article?.article_id}"
        }
    }
}

private class ArticleDiffCallback : DiffUtil.ItemCallback<Article>() {
    override fun areItemsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem.key == newItem.key
    }

    override fun areContentsTheSame(oldItem: Article, newItem: Article): Boolean {
        return oldItem == newItem
    }
}